<script setup>
  import { onMounted, ref } from 'vue'
  import {
    onLoad,
    onShow,
    onReachBottom,
    onPullDownRefresh,
    onShareAppMessage,
  } from '@dcloudio/uni-app'
  import { http } from '@/utils/http.js'
  import Tabbar from '@/components/TabbarCustom.vue'
  import ChooseModel from '@/components/ChooseModel.vue'
  import ProgressBar from '@/components/ProgressBar.vue'
  import { useUsercodeStore } from '@/store/usercode.js'
  const userCodeStore = useUsercodeStore()

  const goodsData = ref([])
  const currentPage = ref(1)
  const chooseRef = ref(null)
  const chooseClassData = ref([])
  const currentClass = ref(undefined)
  const showOfficial = ref(true)
  const orderBy = ref()
  const canLoadMore = ref(true)
  const showBoxRule = ref(['SP1', 'SP2', 'SP3', 'SP4', 'SP5', 'A'])
  async function getList() {
    let params = { page: currentPage.value, limit: 10, type: 1 }
    if (currentClass.value) {
      params.class_id = currentClass.value
    }
    if (orderBy.value) {
      params.order_by = orderBy.value
    }
    if (!showOfficial.value) {
      params.user_id = 1
    }

    const res = await http.request({
      url: '/api/box/boxList',
      method: 'POST',
      data: params,
    })
    console.log(res)
    if (res.st == 1) {
      if (res.data.length < 10) {
        canLoadMore.value = false
      }
      goodsData.value = [...goodsData.value, ...res.data]
    } else {
      canLoadMore.value = false
    }
  }

  async function getBoxCategary() {
    const res = await http.request({
      url: '/api/shop/getClass',
      method: 'POST',
      data: {},
    })
    res.data.forEach((item) => {
      let ob = {
        id: item.id,
        value: item.class_name,
      }
      chooseClassData.value.push(ob)
    })
  }

  async function clearParams() {
    currentClass.value = undefined
    // showOfficial.value = true
    orderBy.value = undefined
    canLoadMore.value = true
  }

  async function clearData() {
    goodsData.value = []
    currentPage.value = 1
  }

  // 上拉加载
  onReachBottom(() => {
    if (canLoadMore.value) {
      currentPage.value++
      getList()
    }
  })

  onMounted(() => {
    // getList()
  })

  onLoad(() => {
    getBoxCategary()
  })

  onShow(() => {
    clearData()
    clearParams()
    getList()
  })

  function gotoTreasureDraw() {
    uni.navigateTo({
      url: `/drawPage/treasureDraw/list`,
    })
  }

  function gotoTianxuanDetail(id) {
    uni.navigateTo({
      url: `/pages/chosen/tianxuan-detail?id=${id}`,
    })
  }
  // 跳转申请入驻
  function gotoSettlein() {
    uni.navigateTo({
      url: `/minePage/settlein/index`,
    })
  }
  // 跳转商家列表
  function gotoMerchantsList() {
    uni.navigateTo({
      url: `/shopPage/shopList/merchants-list`,
    })
  }

  function chooseClass() {
    if (chooseRef.value) {
      chooseRef.value.toggleDropdown()
    }
  }

  function chooseClassAction(id) {
    console.log('重新刷新')
    currentClass.value = id
    clearData()
    getList()
  }

  async function hope(id) {
    if (
      userCodeStore.usercode.token == '' ||
      userCodeStore.usercode.userId == ''
    ) {
      uni.utils.toast('为了让您有更好的体验，请先登录')
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/login/login`,
        })
      }, 2000)
      return
    }

    const res = await http.request({
      url: '/api/goods/scPost',
      method: 'POST',
      data: {
        id: id,
        type: '2',
      },
    })
    console.log(res)
    if (res.st == 1) {
      goodsData.value.forEach((item) => {
        if (item.id == id) {
          if (item.is_sc == 1) {
            item.is_sc = 0
          } else if (item.is_sc == 0) {
            item.is_sc = 1
          }
        }
        console.log(item)
      })
      uni.showToast({
        title: '操作成功',
        duration: 2000,
      })
    } else {
      uni.showToast({
        title: '操作失败',
        icon: 'error',
        duration: 2000,
      })
    }
  }

  const timeAsc = ref(0) // 0: 全部，1：desc，2：asc
  const leftoverAsc = ref(0)
  const priceAsc = ref(0)
  function chooseOrder(order) {
    // 排序 type = 1 | type = 3 传入 price 价格  ， add_time 时间， leftover 进度  price,asc 价格升序 price,desc 价格降序
    if (order == 1) {
      timeAsc.value = timeAsc.value + 1
      if (timeAsc.value > 2) {
        timeAsc.value = 0
      }
      leftoverAsc.value = 0
      priceAsc.value = 0
    }
    if (order == 2) {
      leftoverAsc.value = leftoverAsc.value + 1
      if (leftoverAsc.value > 2) {
        leftoverAsc.value = 0
      }
      timeAsc.value = 0
      priceAsc.value = 0
    }
    if (order == 3) {
      priceAsc.value = priceAsc.value + 1
      if (priceAsc.value > 2) {
        priceAsc.value = 0
      }
      timeAsc.value = 0
      leftoverAsc.value = 0
    }
    convertToOrderBy()
    clearData()
    getList()
  }

  function convertToOrderBy() {
    if (timeAsc.value > 0) {
      if (timeAsc.value == 1) {
        orderBy.value = 'add_time,desc'
      }
      if (timeAsc.value == 2) {
        orderBy.value = 'add_time,asc'
      }
    }
    if (leftoverAsc.value > 0) {
      if (leftoverAsc.value == 1) {
        orderBy.value = 'leftover,desc'
      }
      if (leftoverAsc.value == 2) {
        orderBy.value = 'leftover,asc'
      }
    }
    if (priceAsc.value > 0) {
      if (priceAsc.value == 1) {
        orderBy.value = 'price,desc'
      }
      if (priceAsc.value == 2) {
        orderBy.value = 'price,asc'
      }
    }
  }

  function tabSwith(type) {
    console.log('天选类型切换', type)
    if (type == 1) {
      showOfficial.value = true
      clearData()
      clearParams()
      getList()
    }
    if (type == 2) {
      showOfficial.value = false
      clearData()
      clearParams()
      getList()
    }
  }
</script>

<template>
  <Tabbar :current="3"></Tabbar>
  <view class="luckybox-content">
    <view class="lucky-head">
      <view class="head-img">
        <image
          src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/tianxuan-banner.png"
        ></image>
      </view>
      <!-- 中间 -->
      <view class="head-lable">
        <view class="lable-left">
          <view
            class="official-box"
            :style="{
              border: showOfficial
                ? '2rpx solid #906DDE'
                : '2rpx solid #A6A6A6',
              color: showOfficial ? '#906DDE' : '#A6A6A6',
            }"
            @click="tabSwith(1)"
            >官方天选</view
          >
          <view
            class="business-box"
            :style="{
              border: !showOfficial
                ? '2rpx solid #906DDE'
                : '2rpx solid #A6A6A6',
              color: showOfficial ? '#A6A6A6' : '#906DDE',
            }"
            @click="tabSwith(2)"
            >商家天选</view
          >
        </view>
        <view class="lable-right">
          <view class="goto-bussinesslist" @click="gotoMerchantsList">
            <image
              class=""
              src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/lucky-box/goto-bussinesslist.png"
            >
            </image>
            <text class="bussinesslist-tit">商家列表</text>
          </view>
          <!-- <view class="goto-bussinesslist" @click="gotoSettlein">
						<image class=""
							src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/lucky-box/goto-bussinesscome.png">
						</image>
						<text class="bussinesslist-tit">商家入驻</text>
					</view> -->
          <view class="goto-bussinesslist" @click="gotoTreasureDraw">
            <image
              class=""
              src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/lucky-box/goto-bussinesscome.png"
            >
            </image>
            <text class="bussinesslist-tit">神秘天选</text>
          </view>
        </view>
      </view>
      <!-- 标签 -->
      <view class="classify-list">
        <view class="classify-class" @click="chooseClass">
          <text class="">品类</text>
        </view>
        <view class="classify-time" @click="chooseOrder(1)">
          <text class="" :style="{ color: timeAsc > 0 ? '#906DDE' : '' }"
            >时间</text
          >
          <template v-if="timeAsc == 0">
            <image
              class=""
              src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/lucky-box/sort.png"
            ></image>
          </template>
          <template v-if="timeAsc == 1">
            <image
              class=""
              src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/lucky-box/down.png"
            ></image>
          </template>
          <template v-if="timeAsc == 2">
            <image
              class=""
              src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/lucky-box/up.png"
            ></image>
          </template>
        </view>
        <view class="classify-time" @click="chooseOrder(2)">
          <text class="" :style="{ color: leftoverAsc > 0 ? '#906DDE' : '' }"
            >进度</text
          >
          <template v-if="leftoverAsc == 0">
            <image
              class=""
              src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/lucky-box/sort.png"
            ></image>
          </template>
          <template v-if="leftoverAsc == 1">
            <image
              class=""
              src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/lucky-box/down.png"
            ></image>
          </template>
          <template v-if="leftoverAsc == 2">
            <image
              class=""
              src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/lucky-box/up.png"
            ></image>
          </template>
        </view>
        <view class="classify-time" @click="chooseOrder(3)">
          <text class="" :style="{ color: priceAsc > 0 ? '#906DDE' : '' }"
            >价格</text
          >
          <template v-if="priceAsc == 0">
            <image
              class=""
              src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/lucky-box/sort.png"
            ></image>
          </template>
          <template v-if="priceAsc == 1">
            <image
              class=""
              src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/lucky-box/down.png"
            ></image>
          </template>
          <template v-if="priceAsc == 2">
            <image
              class=""
              src="https://ojqn.wm2177.com/wechat_imgs/kapai-test/lucky-box/up.png"
            ></image>
          </template>
        </view>
      </view>
      <ChooseModel
        ref="chooseRef"
        :items="chooseClassData"
        :current="currentClass"
        @chooseAction="chooseClassAction"
      />
      <!-- 列表 -->
      <view class="business-box-list">
        <view
          class="business-list"
          v-for="(item, index) in goodsData"
          :key="index"
          @click="gotoTianxuanDetail(item.id)"
        >
          <view class="list-left-img">
            <image class="bussiness-img" :src="item.img"></image>
            <image class="level-img" :src="item.class_img"></image>
          </view>
          <view class="list-right-tit">
            <view class="tit-like">
              <view class="">
                <text class="" style="font-size: 28rpx">{{ item.name }}</text>
              </view>
              <view class="" style="margin-right: 10rpx">
                <uni-icons
                  :type="item.is_sc == 0 ? 'heart' : 'heart-filled'"
                  :color="item.is_sc == 1 ? '#EC5050' : ''"
                  size="17"
                  @tap.stop="hope(item.id)"
                ></uni-icons>
              </view>
            </view>
            <!-- 商品数量 -->
            <view class="mid-level">
              <template v-for="(goods, index) in item.box_goods">
                <view
                  class="Leavel-list"
                  v-if="showBoxRule.includes(goods.rule_name)"
                >
                  <view class="level-img">
                    <image :src="goods.rule_img"></image>
                  </view>
                  <view class="leavel-num">
                    <text>{{ goods.leftover }}/{{ goods.num }}</text>
                  </view>
                </view>
              </template>
            </view>
            <!-- 余量 -->
            <view class="list-money">
              <view class="money-now">
                <text class="">￥{{ item.price }}</text>
              </view>
              <view class="money-num">
                <text class="">余</text>
                <text class="" style="color: #af85ff"
                  >{{ item.leftover }}/</text
                >
                <text class="">共</text>
                <text class="" style="color: #af85ff">{{ item.sum }}</text>
              </view>
            </view>
            <ProgressBar
              :progress="((item.sum - item.leftover) / item.sum) * 100"
              style="width: 100%; height: 30rpx"
            />
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
  .luckybox-content {
    background-color: #e9eaf2;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
  }

  .lucky-head {
    width: 730rpx;
    height: 522rpx;
    border-radius: 14rpx;
    background: #ffffff;
    margin: 20rpx auto;

    .head-img {
      width: 674rpx;
      height: 364rpx;
      margin: 10rpx auto;

      image {
        width: 674rpx;
        height: 364rpx;
      }
    }
  }

  .head-lable {
    display: flex;
    justify-content: space-between;
    // margin-left: 20rpx;

    .lable-left {
      display: flex;
      justify-content: space-around;
      width: 50%;
    }

    .official-box,
    .business-box {
      width: 140rpx;
      height: 54rpx;
      text-align: center;
      line-height: 54rpx;
      font-weight: 500;
      border: 2rpx solid #c1a6ff;
      border-radius: 14rpx;
    }

    .business-box {
      color: #a6a6a6;
      border: 2rpx solid #a6a6a6;
    }

    .lable-right {
      display: flex;
      justify-content: space-around;
      width: 40%;
      margin: auto;

      .goto-bussinesslist {
        display: flex;
        border-radius: 14rpx;
        background: #ffffff;
        border: 2rpx solid #c1a6ff;
        width: 126rpx;
        height: 40rpx;
        line-height: 40rpx;
        justify-content: center;
        text-align: center;
        font-size: 20rpx;

        image {
          width: 20rpx;
          height: 23rpx;
          margin: auto;
        }

        .bussinesslist-tit {
          margin: auto;
          color: #906dde;
        }
      }
    }
  }
  .classify-list {
    display: flex;
    justify-content: space-between;
    margin: 20rpx;
    width: 92%;
    font-size: 28rpx;
    .classify-class {
      background-color: #906dde;
      width: 104rpx;
      height: 40rpx;

      line-height: 40rpx;
      text-align: center;
      border-radius: 14rpx;
      color: #fff;
    }
    .classify-time {
      display: flex;
      image {
        width: 13rpx;
        height: 24rpx;
        margin: auto;
        padding-left: 10rpx;
      }
    }
  }

  .business-box-list {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin: 40rpx auto;
    padding-bottom: 200rpx;
    .business-list {
      width: 730rpx;
      height: 260rpx;
      background-color: #fff;
      border-radius: 14rpx;
      margin-bottom: 20rpx;
      display: flex;
      justify-content: space-between;
    }
    .list-left-img {
      width: 60%;
      height: 100%;
      display: flex;
      justify-content: center;
      position: relative;

      .bussiness-img {
        width: 384rpx;
        height: 196rpx;
        margin: auto;
        border-radius: 10rpx;
      }
      .level-img {
        width: 97rpx;
        height: 48rpx;
        position: absolute;
        left: 28rpx;
        top: 14rpx;
        image {
          width: 100%;
          height: 48rpx;
        }
      }
    }
  }
  .list-right-tit {
    width: 40%;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    .tit-like {
      display: flex;
      justify-content: space-between;
      // margin-top: 20rpx;
      image {
        width: 24rpx;
        height: 21rpx;
        margin: auto;
      }
    }
    .mid-level {
      width: 280rpx;
      height: 80rpx;
      border: 3rpx solid #a281eb;
      margin: 0rpx auto;
      border-radius: 10rpx;
      display: flex;
      overflow: auto;

      .Leavel-list {
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        width: 20%;
        height: 80rpx;
        margin: 0rpx 14rpx 0rpx 14rpx;
        .level-img {
          margin-top: 5rpx;
          image {
            width: 62rpx;
            height: 33rpx;
          }
        }
        .leavel-num {
          width: 70rpx;
          height: 30rpx;
          font-size: 16rpx;
          color: #a882ff;
          line-height: 30rpx;
          text-align: center;
          border: 2rpx solid #a882ff;
          // margin-top: 20rpx;
          border-radius: 6rpx;
        }
      }
    }
  }
  .list-money {
    display: flex;
    justify-content: space-between;
    margin-top: 0rpx;
    .money-now {
      font-size: 28rpx;
    }
    .money-num {
      display: flex;
      font-size: 20rpx;
      line-height: 40rpx;
      text-align: center;
      margin-right: 10rpx;
    }
  }
</style>
